package com.alibaba.citrus.ots.forecast.repository.impl;

import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.common.exception.FunctionException;
import com.alibaba.citrus.ots.forecast.common.LogUtils;
import com.alibaba.citrus.ots.forecast.facade.service.ForecastOrderWriteServiceImpl;
import com.alibaba.citrus.ots.forecast.repository.ForecastOrderLineQueryRepository;
import com.alibaba.citrus.ots.forecast.repository.ForecastOrderWriteRepository;
import com.alibaba.citrus.ots.forecast.repository.impl.converter.ForecastOrderRepositoryConverter;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.user.dto.LoginUser;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcots.service.BcOtsService;
import com.epoch.app.otsforecastsales.domian.forecastorder.dto.*;
import com.epoch.app.otsforecastsales.domian.forecastorder.model.ForecastOrder;
import com.epoch.app.otsforecastsales.domian.forecastorder.service.ForecastOrderService;
import com.epoch.app.otsforecastsales.domian.forecastorderline.dto.UpdateForecastOrderLineResponse;
import com.epoch.app.otsforecastsales.domian.forecastorderline.model.ForecastOrderLine;
import com.epoch.app.otsforecastsales.domian.forecastorderline.service.ForecastOrderLineService;
import com.epoch.app.otsforecastsales.enums.ForecastStatusEnum;
import com.epoch.app.otsforecastsales.model.enums.ForecastOrderLogEnum;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.otspricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.otspricecenter.model.dto.CreditReponse;
import com.epoch.app.otspricecenter.model.dto.QueryCreditRequest;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author: qiaojiange
 * @create: 2021/09/15
 * @Description 请描述类的业务用途
 */
@Service
public class ForecastOrderWriteRepositoryImpl implements ForecastOrderWriteRepository {

    @Resource
    ForecastOrderService forcecastOrderService;
    @Resource
    BcOtsService bcOtsService;

    @Resource
    ForecastOrderLineQueryRepository forecastOrderLineQueryRepository;

    @Resource
    private EpochLoginUserService epochLoginUserService;
    @Resource
    ForecastOrderLineService forecastOrderLineService;
    @Resource
    private CreditQueryService creditQueryService;
    private static final Log log = Log.getLogger(ForecastOrderWriteServiceImpl.class);


    /*
     保存主单 王成 21/9/16
     */
    @Override
    public String save(ForecastOrderSDO forecastOrderSDO) {
        //保存主单 TODO 业务渠道与销售渠道的关系  客户地址与客户的级联关系
        ForecastOrder forecastOrder = new ForecastOrder();
        forecastOrder.setOrderBizId(forecastOrderSDO.getOrderBizId());
        forecastOrder.setAreaCode(forecastOrderSDO.getAreaCode());
        forecastOrder.setBisUnitCode(forecastOrderSDO.getBisUnitCode());
        forecastOrder.setSalesmanId(forecastOrderSDO.getSalesmanCode());
        forecastOrder.setSalesmanName(forecastOrderSDO.getSalesmanName());
        forecastOrder.setStatus(forecastOrderSDO.getStatus());
        forecastOrder.setOrderType(forecastOrderSDO.getOrderType());
        if (StringUtils.isNotBlank(forecastOrderSDO.getId())) {
            forecastOrder.setId(Long.parseLong(forecastOrderSDO.getId()));
        }
        forecastOrder.setReceiveAddressCode(forecastOrderSDO.getReceiveAddressCode());
        forecastOrder.setReceiveDetailAddress(forecastOrderSDO.getReceiveDetailAddress());
        forecastOrder.setCustomerCode(forecastOrderSDO.getCustomerCode());
        forecastOrder.setCustomerName(forecastOrderSDO.getCustomerName());
        forecastOrder.setTransportModeCode(forecastOrderSDO.getTransportModeCode());
        forecastOrder.setTransportModeName(forecastOrderSDO.getTransportModeName());
        forecastOrder.setChannelCode(forecastOrderSDO.getChannelCode());
        forecastOrder.setChannelName(forecastOrderSDO.getChannelName());
        forecastOrder.setDepartmentCode(forecastOrderSDO.getDepartmentCode());
        forecastOrder.setDepartmentName(forecastOrderSDO.getDepartmentName());
        forecastOrder.setOrganizationCode(forecastOrderSDO.getOrganizationCode());
        forecastOrder.setOrganizationName(forecastOrderSDO.getOrganizationName());
        forecastOrder.setSaleChannelCode(forecastOrderSDO.getSaleChannelCode());
        forecastOrder.setSaleChannelName(forecastOrderSDO.getSaleChannelName());
        forecastOrder.setCreditBalance(forecastOrderSDO.getCreditBalance());
        forecastOrder.setProductGroupCode(forecastOrderSDO.getProductGroupCode());
        forecastOrder.setProductGroupName(forecastOrderSDO.getProductGroupName());
        forecastOrder.setCreateReason(forecastOrderSDO.getCreateReason());
        forecastOrder.setWareHouseCode(forecastOrderSDO.getWareHouseCode());
        forecastOrder.setWareHouseName(forecastOrderSDO.getWareHouseName());
        forecastOrder.setCustomerReferenceNo(forecastOrderSDO.getCustomerReferenceNo());
        forecastOrder.setRemark(forecastOrderSDO.getRemark());
        forecastOrder.setVaildBeginTime(forecastOrderSDO.getVaildBeginTime());
        forecastOrder.setBizCode("com.mn.demo");
        forecastOrder.setBusinessCode("com.base.line");
        //创建人
        forecastOrder.setCreatorId(forecastOrderSDO.getCreatorId());
        forecastOrder.setCreatorName(forecastOrderSDO.getCreatorName());
        forecastOrder.setModifierId(forecastOrderSDO.getCreatorId());
        forecastOrder.setModifierName(forecastOrderSDO.getCreatorName());
        //联系人
        forecastOrder.setContact(forecastOrderSDO.getContact());
        forecastOrder.setContactPhone(forecastOrderSDO.getContactPhone());
        forecastOrder.setCustomerExpectTDate(forecastOrderSDO.getCustomerExpectTDate());
        forecastOrder.setGmtCreate(forecastOrderSDO.getGmtCreate());
        if (MapUtils.isNotEmpty(forecastOrderSDO.getFeatures())){
            forecastOrder.setFeatures(JSON.toJSONString(forecastOrderSDO.getFeatures()));
        }
        if (StringUtils.isBlank(forecastOrderSDO.getCreditBalance())) {
            try {
                //添加set客户信贷余额
                QueryCreditRequest queryCreditRequest = new QueryCreditRequest();
                queryCreditRequest.setOrganizationCode(forecastOrderSDO.getOrganizationCode());
                queryCreditRequest.setChannelCode(forecastOrderSDO.getChannelCode());
                queryCreditRequest.setItemGroupCode(forecastOrderSDO.getProductGroupCode());
                queryCreditRequest.setCustomerCode(forecastOrderSDO.getCustomerCode());
                log.info("com.alibaba.citrus.ots.forecast.repository.impl.ForecastOrderWriteRepositoryImpl|save|查询信贷入参",
                        JSONObject.toJSONString(queryCreditRequest));
                Result<CreditReponse> creditReponseResult = creditQueryService.queryCreditBalance(queryCreditRequest);
                String balance = "";
                if (Objects.nonNull(creditReponseResult) && Objects.nonNull(creditReponseResult.getResult()) &&
                        Objects.nonNull(creditReponseResult.getResult().getBalance())) {
                    balance = creditReponseResult.getResult().getBalance();
                }
                forecastOrder.setCreditBalance(balance);
            } catch (FunctionException e) {
                log.error("com.alibaba.citrus.ots.forecast.repository.impl.ForecastOrderWriteRepositoryImpl#save", e);
            }
        }
        CreateForecastOrderResponse createForecastOrderResponse = forcecastOrderService.createForecastOrder(forecastOrder);
        String lastInsertId = createForecastOrderResponse.getLastInsertId();
        if (StringUtils.isEmpty(lastInsertId)) {
            log.error("ForecastOrderWriteRepositoryImpl#save_fail");
        }
        return lastInsertId;
    }


    @Override
    public boolean submit(ForecastOrderSDO forecastOrderSDO) {
        LoadForecastOrderRequest loadForecastOrderRequest = new LoadForecastOrderRequest();
        loadForecastOrderRequest.setId(forecastOrderSDO.getId());
        ForecastOrder forecastOrder = forcecastOrderService.loadForecastOrder(loadForecastOrderRequest);
        forecastOrder.setId(Long.parseLong(forecastOrderSDO.getId()));
        forecastOrder.setId(Long.parseLong(forecastOrderSDO.getId()));
        forecastOrder.setStatus(forecastOrderSDO.getStatus());
        forecastOrder.setModifierId(forecastOrderSDO.getModifierId());
        forecastOrder.setModifierName(forecastOrderSDO.getModifierName());
        forecastOrder.setVaildBeginTime(forecastOrderSDO.getVaildBeginTime());
        UpdateForecastOrderResponse updateForecastOrderResponse = forcecastOrderService.updateForecastOrder(forecastOrder);
        Integer count = updateForecastOrderResponse.getCount();
        if (0 == count) {
            log.error("ForecastOrderWriteRepositoryImpl#submit_fail");
            return false;
        }
        return true;
    }

    /*
     更改预报单 王成 21/9/16
     */
    @Override
    public boolean modify(ForecastOrderSDO forecastOrderSDO) {
        ForecastOrder forecastOrder = new ForecastOrder();
        forecastOrder.setId(Long.parseLong(forecastOrderSDO.getId()));
        if (StringUtils.isNotBlank(forecastOrderSDO.getReceiveAddressCode())) {
            forecastOrder.setReceiveAddressCode(forecastOrderSDO.getReceiveAddressCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getCustomerCode())) {
            forecastOrder.setCustomerCode(forecastOrderSDO.getCustomerCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getTransportModeCode())) {
            forecastOrder.setTransportModeCode(forecastOrderSDO.getTransportModeCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getChannelCode())) {
            forecastOrder.setChannelCode(forecastOrderSDO.getChannelCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getDepartmentCode())) {
            forecastOrder.setDepartmentCode(forecastOrderSDO.getDepartmentCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getOrganizationCode())) {
            forecastOrder.setOrganizationCode(forecastOrderSDO.getOrganizationCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getSaleChannelCode())) {
            forecastOrder.setSaleChannelCode(forecastOrderSDO.getSaleChannelCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getCreditBalance())) {
            forecastOrder.setCreditBalance(forecastOrderSDO.getCreditBalance());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getProductGroupCode())) {
            forecastOrder.setProductGroupCode(forecastOrderSDO.getProductGroupCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getCreateReason())) {
            forecastOrder.setCreateReason(forecastOrderSDO.getCreateReason());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getWareHouseCode())) {
            forecastOrder.setWareHouseCode(forecastOrderSDO.getWareHouseCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getCustomerReferenceNo())) {
            forecastOrder.setCustomerReferenceNo(forecastOrderSDO.getCustomerReferenceNo());
        }
        forecastOrder.setRemark(forecastOrderSDO.getRemark());
        if (null != forecastOrderSDO.getCustomerExpectTDate()) {
            forecastOrder.setCustomerExpectTDate(forecastOrderSDO.getCustomerExpectTDate());
        }
        if (null != forecastOrderSDO.getVaildBeginTime()) {
            forecastOrder.setVaildBeginTime(forecastOrderSDO.getVaildBeginTime());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getModifierId())) {
            forecastOrder.setModifierId(forecastOrderSDO.getModifierId());
        }

        if (StringUtils.isNotBlank(forecastOrderSDO.getModifierName())) {
            forecastOrder.setModifierName(forecastOrderSDO.getModifierName());
        }

        if (Objects.nonNull(forecastOrderSDO.getGmtModified())) {
            forecastOrder.setGmtModified(forecastOrderSDO.getGmtModified());
        }
        LoadForecastOrderRequest loadForecastOrderRequest1 = new LoadForecastOrderRequest();
        loadForecastOrderRequest1.setId(forecastOrderSDO.getId());
        forecastOrder.setStatus(forecastOrderSDO.getStatus());
        UpdateForecastOrderResponse updateForecastOrderResponse = forcecastOrderService.updateForecastOrder(forecastOrder);
        Integer count = updateForecastOrderResponse.getCount();
        if (0 == count) {
            log.error("ForecastOrderWriteRepositoryImpl#modify_fail");
            log.error("ForecastOrderWriteRepositoryImpl|modify|更新主单失败日志", forecastOrder.getId());
            throw new RuntimeException("预报主单信息更新失败");
        }
        return true;
    }

    @Override
    public boolean modifyForecast(ForecastOrderSDO forecastOrderSDO) {
        boolean isSuccess=true;
        LoadForecastOrderRequest loadForecastOrderRequest = new LoadForecastOrderRequest();
        loadForecastOrderRequest.setId(forecastOrderSDO.getId());
        ForecastOrder forecastOrder = forcecastOrderService.loadForecastOrder(loadForecastOrderRequest);
        //客户收货地址
        if (StringUtils.isNotBlank(forecastOrderSDO.getReceiveAddressCode())) {
            forecastOrder.setReceiveAddressCode(forecastOrderSDO.getReceiveAddressCode());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getCustomerReferenceNo())) {
            forecastOrder.setCustomerReferenceNo(forecastOrderSDO.getCustomerReferenceNo());
        }
        if (StringUtils.isNotBlank(forecastOrderSDO.getCustomerCode())) {
            forecastOrder.setCustomerCode(forecastOrderSDO.getCustomerCode());
        }
        //配送方式
        if (StringUtils.isNotBlank(forecastOrderSDO.getTransportModeCode())) {
            forecastOrder.setTransportModeCode(forecastOrderSDO.getTransportModeCode());
        }
        //单据原因
        if (StringUtils.isNotBlank(forecastOrderSDO.getCreateReason())) {
            forecastOrder.setCreateReason(forecastOrderSDO.getCreateReason());
        }
        //备注
        if (StringUtils.isNotBlank(forecastOrderSDO.getRemark())) {
            forecastOrder.setRemark(forecastOrderSDO.getRemark());
        }
        //客户参考日期
        if (null != forecastOrderSDO.getCustomerExpectTDate()) {
            forecastOrder.setCustomerExpectTDate(forecastOrderSDO.getCustomerExpectTDate());
        }
        //发货仓库
        if (StringUtils.isNotBlank(forecastOrderSDO.getWareHouseName())) {
            forecastOrder.setWareHouseName(forecastOrderSDO.getWareHouseName());
        }
        if (null != forecastOrderSDO.getStatus()) {
            forecastOrder.setStatus(forecastOrderSDO.getStatus());
        }

        if (null != forecastOrderSDO.getRefuseStatus()) {
            forecastOrder.setRefuseStatus(forecastOrderSDO.getRefuseStatus());
        }
        LoadForecastOrderRequest loadForecastOrderRequest1=new LoadForecastOrderRequest();
        loadForecastOrderRequest1.setId(forecastOrderSDO.getId());
        UpdateForecastOrderResponse updateForecastOrderResponse = forcecastOrderService.updateForecastOrder(forecastOrder);
        Integer count = updateForecastOrderResponse.getCount();
        if (0 == count) {
            log.error("ForecastOrderWriteRepositoryImpl#modifyForecast_fail");
            log.error("ForecastOrderWriteRepositoryImpl|modifyForecast|更新主单失败日志",forecastOrder.getId());
            throw new RuntimeException("预报主单信息更新失败");
        }
        return true;
    }

    /**
     * 批量更改 王成 21/9/16
     */
    @Override
    @EpochTransactional(appCode = "ots_forecast_sales", dataSourceCode = "cr_ots")
    public Integer batchModify(List<String> ids) {
        BatchModifyByIdsRequest batchModifyByIdsRequest = new BatchModifyByIdsRequest();
        batchModifyByIdsRequest.setIds(ids);
        BatchModifyByIdsResponse batchModifyByIdsResponse = forcecastOrderService.batchModifyByIds(batchModifyByIdsRequest);
        Integer count = batchModifyByIdsResponse.getCount();
        if (0 == count) {
            log.error("ForecastOrderWriteRepositoryImpl#batchModify_fail");
            log.error("ForecastOrderWriteRepositoryImpl|batchModify|批量修改主单状态失败",ids);
            throw new RuntimeException("预报主单信息更新失败");
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateForecastStatus(List<ForecastOrderLineSDO> orderLineList, ForecastOrderSDO order) {
        LoginUser loginUser = epochLoginUserService.getLoginUser();
        // 更新预报子单
        for (ForecastOrderLineSDO sdo : orderLineList) {
            ForecastOrderLine forecastOrderLine = ForecastOrderRepositoryConverter.toForecastOrderLine(sdo);
            log.info("更新的预报子单信息:" + JSONObject.toJSONString(forecastOrderLine));
            UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
            Integer count = updateForecastOrderLineResponse.getCount();
            if(count==0){
                log.error("ForecastOrderWriteRepositoryImpl#updateForecastStatus_fail");
                log.error("ForecastOrderWriteRepositoryImpl|updateForecastStatus|预报子单信息更新失败",JSONObject.toJSONString(forecastOrderLine));
                throw new RuntimeException("预报子单信息更新失败");
            }
        }
        // 更新预报主单
        ForecastOrderLineSDO tmp = new ForecastOrderLineSDO();
        tmp.setMainOrderId(order.getId());
        List<ForecastOrderLineSDO> forecastOrderLines= forecastOrderLineQueryRepository.queyrLineDetailList(tmp);
        ForecastOrderSDO sdo = updateForecastOrderStatus(forecastOrderLines, order);
        boolean b = modify(sdo);
        LogUtils.printOperateLog(sdo.getId(),ForecastOrderLogEnum.EDIT.getForecastOrderLogValue(),"编辑预报订单",loginUser);
        if (b) {
            return true;
        } else {
            log.error("ForecastOrderWriteRepositoryImpl#updateForecastStatus_fail");
            log.error("ForecastOrderWriteRepositoryImpl|updateForecastStatus|预报主单信息更新失败",JSONObject.toJSONString(tmp));
            throw new RuntimeException("预报主单信息更新失败");
        }
    }

    public ForecastOrderSDO updateForecastOrderStatus(List<ForecastOrderLineSDO> forecastOrderLines, ForecastOrderSDO forecastOrder) {
        for (ForecastOrderLineSDO orderLine: forecastOrderLines){
            if ((orderLine.getStatus().equals(ForecastStatusEnum.PARTIAL_REPLY.getNumValue()))) {
                forecastOrder.setStatus(ForecastStatusEnum.PARTIAL_REPLY.getNumValue());
                return forecastOrder;
            }
        }
        // todo 除了部分回复，其它都是等待回复
        forecastOrder.setStatus(ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue());
        return forecastOrder;
    }

}
